<template>
  <div class="whom mbm bt_line">
    <h4 class="step_title mbm">第二步，别人怎么称呼我：</h4>
    <div class="mbm">
      <a-button class type="primary" @click="showModalUser({},$event)"><a-icon type="user-add" /> 新增用户</a-button>
    </div>

    <a-tabs type="editable-card" hideAdd v-model="activeKey" @edit="onEdit" size="small">
      <a-tab-pane
        v-for="(pane,idx) in panes"
        :tab="pane.title"
        :key="pane.key"
        :closable="pane.closable"
      >
        <p>{{pane.content}}</p>
        <div class="mbm">
          <template v-for="(tag) in pane.tags">
            <a-tag
              v-if="tag.call && tag.call.length > 10"
              :key="tag.id"
              :closable="true"
              :afterClose="() => handleClose(pane.key,tag)"
            >{{`${tag.call.slice(0, 10)}...`}}</a-tag>
            <a-tag
              v-else
              :key="tag.id"
              :closable="true"
              :afterClose="() => handleClose(pane.key,tag)"
            >{{tag.call}}</a-tag>
          </template>
          <a-input
            v-if="pane.inputVisible"
            :ref="`inputTag_`+idx"
            type="text"
            size="small"
            :style="{ width: '78px' }"
            :value="pane.inputValue"
            @change="handleInputTagChange(idx,$event)"
            @blur="handleInputTagConfirm(pane,$event)"
            @keyup.enter="handleInputTagConfirm(pane,$event)"
          />
          <a-tag
            v-else
            @click="showInput(idx,$event)"
            style="background: #fff; borderStyle: dashed;"
          >
            <a-icon type="plus" />新增称呼
          </a-tag>
        </div>
        <div class="edit_user_btn">
          <template v-if="pane.tel != ''">
            <span class="push_ok mrs">
              <a-icon type="notification" />
              当前已经开启通知 [{{formatPhone(pane.tel)}}]
            </span>
          </template>
          <template v-else>
            <span class="push_no mrs">当前未开启通知</span>
          </template>
          <a @click="showModalUser(pane,$event)"><a-icon type="setting" /> 设置</a>
        </div>
      </a-tab-pane>
    </a-tabs>

    <a-modal
      :title="modalUserTitle"
      :visible="visibleUser"
      @ok="submitUser"
      :confirmLoading="loadingUser"
      @cancel="cancelUser"
      :footer="null"
      :mask="true"
      :maskClosable="false"
    >
      <a-form :form="formUser" @submit="submitUser">
        <a-form-item label="用户标识" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" extra>
          <a-input
            class="talk_input mrm"
            style="width: 160px"
            placeholder="如：“我”，“老婆”，“老王”。"
            :disabled="panes.length===0"
            v-decorator="['title',{ rules: [{ required: true, message: '必须输入用户标识！' }] }]"
          />
        </a-form-item>

        <a-form-item
          label="手机号码"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
          extra="用于收取设备发出的短信通知"
        >
          <a-input
            class="talk_input mrm"
            style="width: 220px"
            placeholder="请输入可以接收短信的手机号"
            v-decorator="['tel',{ rules: [{ pattern:new RegExp('(\(\\d{3,4}\)|\\d{3,4}-|\\s)?\\d{7,14}'), message: '请输入正确的手机格式！' }] }]"
          />
        </a-form-item>
        <a-form-item v-if="editUser.vUid" :wrapper-col="{ span: 12, offset: 5 }">
          <a-button class="mbm" type="primary" html-type="submit">立即修改</a-button>
        </a-form-item>
        <a-form-item v-else :wrapper-col="{ span: 12, offset: 5 }">
          <a-button class="mbm" type="primary" html-type="submit">立即新增</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import tools from "@/utils/tools";
export default {
  data() {
    const panes = [      
    ];
    const user = {
      vKey: 0,
      vUid: 0,
      vTitle: "",
      vTel: ""
    };
    return {
      formUser: this.$form.createForm(this, { name: "form_user" }),
      activeKey: 0,
      panes,
      editUser: user,
      newTabIndex: 0,
      visibleUser: false,
      loadingUser: false,
      modalUserTitle: "",      
    };
  },
  computed:{
    formCheck(){
      if (this.panes.length > 0 && this.panes[0].tags.length > 0){
        return 0
      }else{
        return 1
      }
    }
  },
  mounted: function() {
    this.loadUser();
  },
  methods: {
    //标签页
    onEdit(targetKey, action) {
      this[action](targetKey);
    },
    newPane(v, i) {
      if (typeof(v.username) == "undefined") {
        v.username= `用户${i}`;
      }
      return {
        key: i,
        title: i === 0 ? `我自己` : v.username,
        content:
          i === 0
            ? `请在下方填写陌生来电对您的常用称呼，如赵总，钱先生，孙小姐，李哥...`
            : `用于朋友或家人共享一台设备，请输入主叫方对他的常用称呼...`,
        closable: i === 0 ? false : true,
        tags: v.call?v.call:[],
        inputVisible: false,
        inputValue: "",
        tel: v.tel,
        uid: v.uid
      };
    },
    editPane(v, i) {
      this.panes[i].title = v.username
      this.panes[i].tel = v.tel
    },
    add(v) {
      var panes = this.panes;
      var activeKey = panes.length;      
      panes.push(this.newPane(v, activeKey));
      this.panes = panes;
      this.activeKey = activeKey;
      this.editUser.vTitle = "";
    },
    remove(targetKey) {
      var _that = this;
      this.$confirm({
        title: "您确认要删除这个用户吗?",
        content: "注意，删除操作将清空所有称呼，且不可找回。",
        okType: "danger",
        onOk() {
          let activeKey = _that.activeKey;
          let lastIndex;
          let _uid = 0;
          _that.panes.forEach((pane, i) => {
            if (pane.key === targetKey) {
              lastIndex = i - 1;
              _uid = pane.uid;
            }
          });
          if (parseInt(_uid) > 0) {
            _that.$api.talk
              .delUser({
                uid: _uid
              })
              .then(() => {
                const panes = _that.panes.filter(
                  pane => pane.key !== targetKey
                );
                if (panes.length && activeKey === targetKey) {
                  if (lastIndex >= 0) {
                    activeKey = panes[lastIndex].key;
                  } else {
                    activeKey = panes[0].key;
                  }
                }
                _that.panes = panes;
                _that.activeKey = activeKey;
              });
          }
        },
        onCancel() {}
      });
    },
    showModalUserOk(pane) {
      this.visibleUser = true;
      if (typeof pane.uid != "undefined") {
        this.modalUserTitle = "修改用户";
        this.editUser.vKey = pane.key;
        this.editUser.vUid = pane.uid;
        this.editUser.vTitle = pane.title;
        this.editUser.vTel = pane.tel;
      } else {
        this.modalUserTitle = "新增用户";
        this.editUser.vKey = this.panes.length;
        this.editUser.vUid = 0;
        this.editUser.vTitle = this.panes.length===0?"我自己":"";
        this.editUser.vTel = "";
      }
      this.$nextTick(function() {
        this.formUser.setFieldsValue({
          title: this.editUser.vTitle,
          tel: this.editUser.vTel
        });
      });
    },
    showModalUser(pane) {
      var _that = this;
      if (this.panes.length >= 5) {
        this.$confirm({
          title: "注意，超载了！",
          content:
            "您已经新增了5名用户，新增太多人会造成识别不准确，而且非常不建议您将当前设备上的呼转号码告知太多人。",
          okText: "仍要继续",
          cancelText: "取消",
          okType: "danger",
          onOk() {
            _that.showModalUserOk(pane);
          },
          onCancel() {}
        });
      } else {
        this.showModalUserOk(pane);
      }
    },
    cancelUser() {
      this.visibleUser = false;
    },
    submitUser(e) {
      e.preventDefault();
      this.formUser.validateFields((err, values) => {
        if (!err) {          
          var _key = this.editUser.vKey;
          var _uid = this.editUser.vUid;          
          this.$api.talk
            .addOrUpdateUser({
              uid: _uid ? parseInt(_uid) : 0,
              username: values.title,
              tel: values.tel
            })
            .then(u => {
              this.editUser.vUid = u.uid;
              if (_uid > 0) {
                this.editPane(u, _key)
              } else {
                this.add(u);
              }

              this.visibleUser = false;
            })
            .catch(err => {
              console.log(err);
            });
        }
      });
    },
    loadUser() {
      this.$api.talk
        .getUserList()
        .then(ulist => {
          var panes = [];
          ulist.forEach((v, i) => {
            panes.push(this.newPane(v, i));
          });
          this.activeKey = 0;
          this.panes = panes;
        })
        .catch(err => {
          console.log(err);
        });
    },
    //标签tag
    handleClose(key, removedTag) {
      var _that = this;
      let _id = removedTag.id;

      if (parseInt(_id) > 0) {
        _that.$api.talk
          .delCall({
            id: _id
          })
          .then(res => {
            if (res) {
              const tags = _that.panes[key].tags.filter(
                tag => tag.id !== removedTag.id
              );
              _that.panes[key].tags = tags;
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },

    showInput(k) {
      this.panes[k].inputVisible = true;
      this.$nextTick(function() {
        //console.log(this.$refs);
        this.$refs[`inputTag_` + k][0].focus();
      });
    },

    handleInputTagChange(k, e) {
      this.panes[k].inputValue = e.target.value;
    },

    async handleInputTagConfirm(pane) {
      const _inputValue = this.panes[pane.key].inputValue;
      let _tags = this.panes[pane.key].tags;
      let _uid = pane.uid;
      if (_inputValue && _tags.indexOf(_inputValue) === -1) {
        await this.$api.talk
          .addCall({
            uid: _uid ? parseInt(_uid) : 0,
            call: _inputValue
          })
          .then(data => {
            //console.log(data);
            _tags = [..._tags, { call: data.call, id: data.id }];
          })
          .catch(err => {
            console.log(err);
          });
      }
      Object.assign(this.panes[pane.key], {
        tags: _tags,
        inputVisible: false,
        inputValue: ""
      });
    },
    formatPhone(tel) {
      return tools.formatPhone(tel);
    }
  }
};
</script>

<style lang="less" scoped>
.whom {
  .edit_user_btn {
  font-size: 12px;
  color: #666;
  .push_no {
    color: #ff0000;
  }
  .push_ok{
    color: #000;
  }
}
}

</style>